#!/bin/sh
set -e
local="/home/lich/site/"
gopher_location="$local/public_gopher/musings/"
html_location="$local/public_html/musings/"
remote="/home/lich/"
server="dataswamp"
page="dataswamp.org"
sync_command="rsync -aPulK $local/* $server:$remote"
html_processor="markdown"

htmlgen() {
	printf "<!DOCTYPE html><html lang=\"en\">\n<head><meta charset=\"utf-8\">\n<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"favicon.ico\" />"
	printf "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
	printf "<link rel=stylesheet href="../static/css/main.css">\n<title>%s</title>\n" "$(sed -n "3p" $1)"
	printf "</head>\n<body>\n<article>\n"
	printf "<p><small><em>%s</em></small></p>" "$(date -d$2 -R)"
	sed -n '3,$p' "$1" | $html_processor
	printf "</article><p><small><a href="index.html">Back to the index</a></small></p></body></html>"
	git add "$1"
}

htmlnew() {
	{
	printf "/tbody\na\n"
	printf "<tr><td><a href=\"%s\">%s</a></td></tr>\n.\nw\nq\n" "$2" "$1"
	} | ed -s "$html_location/index.html"
	git add "$html_location/index.html"
}

atomnew() {
	{
	printf "10\n"
	printf "i\n\n\t<entry>\n"
	printf "\t\t<id>%s</id>\n" "$2"
	printf "\t\t<title><![CDATA[%s]]></title>\n" "$1"
	printf "\t\t<link href=\"%s\" />\n" "$2"
	printf "\t\t<content type=\"text\"><![CDATA["
	cat "$3"
	printf "]]></content>\n"
	printf "\t\t<updated>%s</updated>\n" "$4"
	printf "\t</entry>\n.\nw\nq\n"
	} | ed -s "$5"
	git add "$5"
}

gophernew() {
	{
	printf "/MUSINGS\n+2\n"
	printf "i\n[0|%s|%s|%s|70]\n.\nw\nq\n" "$1" "$2" "$3"
	} | ed -s "$gopher_location/../index.gph"
	git add "$gopher_location/../index.gph"
}

post() {
	date="$(sed '1 s/# //;q' $1)"
	title="$(sed '3q;d' $1)"
	htmlgen $1 $date > $html_location/${1%md}html
	gophernew "$title" "/~lich/musings/$1" "$page"
	atomnew "$title" "gopher://$server.org/0/~lich/musings/$1" "$1" "$date" "$gopher_location/../musings.atom.xml"
	htmlnew "$title" "${1%md}html"
	atomnew "$title" "https://dataswamp.org/~lich/musings/${1%md}html" "$1" "$date" "$html_location/musings.atom.xml"
	git commit -m "New post: $1"
	$sync_command
	}

atom_rev() {
	printf "/%s\n" "${1%md}"
	printf "+3\n"
	printf ".,+%sd\n" "$(cat $gopher_location/$1 | wc -l)"
	printf "i\n"
	printf "\t\t<content type=\"text\"><![CDATA["
	cat "$1"
	printf "]]></content>\n.\n\n"
	printf "d\n"
	printf "i\n"
	printf "\t\t<updated>%s</updated>\n.\nw\nq\n" "$date"
}

revise() {
	date="$(date -Iseconds)"
	atom_rev "$1" | ed -s "$gopher_location/../musings.atom.xml"
	atom_rev "$1" | ed -s "$html_location/musings.atom.xml"
	git add "$gopher_location/../musings.atom.xml" "$html_location/musings.atom.xml"
	htmlgen "$1" "$date" > $html_location/${1%md}html
	git commit -m 'Revised $1'
	$sync_command
}

case "$1" in
	n*) post "$2" ;;
	r*) revise "$2" ;;
esac
